﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using Emgu.CV;
using Emgu.Util;
using Emgu.CV.Structure;
using Emgu.CV.CvEnum;
using System.Windows.Forms;

namespace FaceFromCamera
{
    class PersonControler
    {
        #region SingleTon
        static PersonControler instance;
        public static PersonControler Instance
        {
            get
            {
                if (instance == null)
                    instance = new PersonControler();
                return instance;
            }
        }

        #endregion
        public delegate void ModelChangeDelegate(object sender, Person e);
        public event ModelChangeDelegate ModelChangeEvent;

        public void RegisterView(IView view)
        {
            this.ModelChangeEvent += new ModelChangeDelegate(view.ModelChange);
        }
        public void UnregisterView(IView view)
        {
            this.ModelChangeEvent -= new ModelChangeDelegate(view.ModelChange);
        }

        public void RaiseModelChange(object sender, Person e)
        {
            if (ModelChangeEvent != null)
                ModelChangeEvent(sender, e);
        }
        public string[] GetUsernames()
        {
            return DatabaseModel.Instance.GetUsernames();
        }
        
        public void Save(Person person, Image[] faces)
        {
            DatabaseModel.Instance.AddPersonToDatabase(person);
            int id = DatabaseModel.Instance.GetIdFromDatabase(person.login)[0];
            DatabaseModel.Instance.AddPhotosToDatabase(id, faces);
        }
        public void Update(Person person, Image[] faces)
        {
            DatabaseModel.Instance.RemovePerson(person);
            int id = DatabaseModel.Instance.GetIdFromDatabase(person.login)[0];
            DatabaseModel.Instance.AddPhotosToDatabase(id, faces);
        }
        public Person GetUser(string p)
        {
            try
            {
                int id = DatabaseModel.Instance.GetIdFromDatabase(p)[0];
                return DatabaseModel.Instance.GetUser(id);
            }
            catch (Exception e)
            {
                MessageBox.Show("There is no user with specific login","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
                return new Person();
            }
        }
        public Person GetUser(int id)
        {
            return DatabaseModel.Instance.GetUser(id);
        }
        public Image[] UserPictures(int id)
        {
            return DatabaseModel.Instance.GetImage(id).ToArray();
        }
        public void AddPicture(Image p, int id)
        {
            Image[] tab = new Image[1];
            tab[0] = p;
            DatabaseModel.Instance.AddPhotosToDatabase(id, tab);
        }
    }
}
